package io.chenglicun.common.trans.advice;

import cn.hutool.core.util.TypeUtil;
import io.chenglicun.common.trans.annotation.AutoTrans;
import io.chenglicun.common.trans.util.TransUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

@Slf4j
@ControllerAdvice
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class TransResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter parameter, Class converterType) {
        return parameter.hasMethodAnnotation(AutoTrans.class);
    }

    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter parameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (obj == null) {
            return null;
        }
        try {
            TransUtil.trans(obj, getObjClass(parameter));
        } catch (Exception e) {
            log.error("翻译错误", e);
        }
        return obj;
    }

    private Class<?> getObjClass(MethodParameter parameter) {
        Type type = parameter.getGenericParameterType();
        while (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            type = pType.getActualTypeArguments()[0];
        }
        return TypeUtil.getClass(type);
    }
    
}
